package com.atguigu.tingshu.common.factory;

import lombok.Getter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class ScheduleTaskThreadFactory {
    // 创建一个延时线程
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    // 定义一个实例对象
    @Getter
    private  static ScheduleTaskThreadFactory Instance = new ScheduleTaskThreadFactory();
    //私有构造器(禁止外部实例化)
    private ScheduleTaskThreadFactory(){

    }

    /**
     * 定义执行任务的方式：延时任务
     * @param r 执行任务
     * @param ttl 延时时间
     * @param timeUnit 时间单位
     */
    public void execute(Runnable r, Long ttl, TimeUnit timeUnit){
        scheduledExecutorService.schedule(r,ttl,timeUnit);
    }

    /**
     * 计算当前时间与一周后2:00时间的差值
     * @param currentTime 当前时间
     * @return 时间差值
     */
    public long getDiffTime(Long currentTime,Integer day, Integer hour,Integer minute,Integer second){
        LocalDate localDate = LocalDate.now().plusDays(day);
        LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.of(hour, minute, second));
        long endTime = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        return Math.abs(endTime - currentTime);
    }
}
